package com.manager.controller;

import com.manager.bean.Account;
import com.manager.bean.Manager;
import com.manager.bean.Student;
import com.manager.service.AccountService;
import com.manager.service.ManagerService;
import com.manager.service.StudentService;
import com.manager.util.MD5Utils;
import com.manager.util.SendEmail;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

import com.manager.bean.PageInfo;

/**
 * (Account)表控制层
 *
 * @author makejava
 * @since 2021-03-02 20:15:29
 */
@Controller
public class AccountController {
    /**
     * 服务对象
     */
    @Resource
    private AccountService accountService;

    @Resource
    private ManagerService managerService;

    @Resource
    private StudentService studentService;

    @RequestMapping(value="/")
    public String index(HttpSession session,Model model){
        Object user = session.getAttribute("info");
        if(user!=null){
            switch (session.getAttribute("identity").toString()){
                case "student":
                    model.addAttribute("ad",(Account)session.getAttribute("ad"));
                    model.addAttribute("info",(Student)user);
                    return "student_homepage";
                case "teacher":
                    model.addAttribute("ad",(Account)session.getAttribute("ad"));
                    model.addAttribute("info",(Manager)user);
                    return "housemaster_homepage";
                case "root":
                    model.addAttribute("ad",(Account)session.getAttribute("ad"));
                    return "root_homepage";
            }
        }
        model.addAttribute("msg", "请输入账号和密码");
        return "login";
    }
    @RequestMapping(value = "/index")
    public String login( Account admin, Model model, HttpSession session, HttpServletRequest request) {
        // 通过账号和密码查询用户
        String password=admin.getPassword();
        Account user = accountService.queryById(admin.getAccount());
        if (user == null){
            model.addAttribute("msg", "请输入账号和密码");
            return "login";
        }
        String salt=user.getSalt();
        //admin.setPassword();
        //Account ad = accountService.(admin);
        if(MD5Utils.md5(password+salt).equals(user.getPassword())){
            session.setAttribute("ad", user);
            model.addAttribute("ad",user);
            if("student".equals(user.getIdentity())){
                Student student = studentService.queryById(admin.getAccount());
                session.setAttribute("info", student);
                model.addAttribute("info",student);
                session.setAttribute("identity", "student");
                return "student_homepage";
            }
            if("housemaster".equals(user.getIdentity())){
                Manager manager = managerService.queryById(admin.getAccount());
                session.setAttribute("info", manager);
                model.addAttribute("info",manager);
                session.setAttribute("identity", "manager");
                return "housemaster_homepage";
            }
            if("root".equals(user.getIdentity())){
                session.setAttribute("identity", "root");
                return "root_homepage";
            }
            else{
                session.removeAttribute("ad");
                model.addAttribute("msg", "出现未知错误，请联系管理员");
                return "login";
            }
        }
        model.addAttribute("msg", "账号或密码错误，请重新登录！");
        return "login";
    }

    @RequestMapping(value = "/logout")
    public String loginOut(Account admin, Model model, HttpSession session) {
        session.invalidate();
        model.addAttribute("msg", "账号已退出登录");
        return "login";

    }
    @RequestMapping(value = "/findAccount")
    public String findAccount( Model model) {
        PageInfo<Account> pi = null;
        model.addAttribute("pi", pi);
        return "account_list";
    }


    @RequestMapping(value = "/exportaccountServicelist", method = RequestMethod.POST)
    @ResponseBody
    public List<Account> exportAccount() {
        List<Account> accountList = accountService.getAll();
        return accountList;
    }


    @RequestMapping("/deleteAccount")
    @ResponseBody
    public String deleteAccount(Integer Id) {
        Account s = accountService.queryById(Id);
        return "account_list";
    }


    @RequestMapping(value = "/addAccount", method = RequestMethod.POST)
    @ResponseBody
    public String addAccount(@RequestBody Account account) {
        Account s = accountService.insert(account);
        return "account_list";
    }


    @RequestMapping(value = "/updateAccount", method = RequestMethod.POST)
    public String updateAccount(Account account) {
        Account s = accountService.update(account);
        return "redirect:/findAccount";
    }


    @RequestMapping("/findAccountById")
    public String findAccountById(Integer Id, HttpSession session, Model model) {
        boolean s = accountService.deleteById(Id);
        session.setAttribute("s", s);
        model.addAttribute("s", s);
        return "account_edit";
    }


    //转到输入账号页面
    @GetMapping("ForgetPd")
    public  String ForgetPd1(HttpSession session){
        return "ForgetPd1";
    }

    //判断有无邮箱，有则发送验证码，再转到下一页面输入新密码
    @RequestMapping("ForgetPd2")
    public  String ForgetPd2(@RequestParam("account")Integer account,
                             HttpSession session,Model model){
        session.setAttribute("account",account);
        Account s1=accountService.queryById(account);

        Integer a=0;
        if(s1!=null){
            String identity = s1.getIdentity();
            switch (identity){
                case "student":
                    String email = studentService.queryById(s1.getAccount()).getEmail();
                    a=new SendEmail().emailRandomSend(email);
                    session.setAttribute("role","student");
                    break;
                case "housemaster":
                    String email2 = managerService.queryById(s1.getAccount()).getEmail();
                    a=new SendEmail().emailRandomSend(email2);
                    session.setAttribute("role","manager");
                    break;
                case "root":
                    break;
            }
            session.setAttribute("EmailCode",a);
            Date data=new Date();
            session.setAttribute("CodeTime",data.getTime()+180000);
            return "ForgetPd2";
        }

        model.addAttribute("failed","未设置邮箱，请先设置邮箱或者寻找管理员修改密码");
        // return "ForgetPd2";
        return "error/failed";
    }

    //更新密码
    @PostMapping("ChangePassword")
    public String ChangePassword(@RequestParam("EmailCode")Integer UserCode,@RequestParam("password1")String password1,
                                 @RequestParam("password2")String password2,
                                 HttpSession session,Model model){
        if(!password1.equals(password2)){
            model.addAttribute("failed","两次密码输入不一致");
            return "error/failed";
        }
        Date date=new Date();
        if(date.getTime()>(long)session.getAttribute("CodeTime")){
            model.addAttribute("failed","验证码过期");
            return "error/failed";
        }
        if(!UserCode.equals((Integer)session.getAttribute("EmailCode"))){
            model.addAttribute("failed","验证码不一致");
            return "error/failed";
        }
        Account account=accountService.queryById((Integer) session.getAttribute("account"));
        String salt=MD5Utils.getSalt();
        String hash=MD5Utils.md5(password1+salt);
        account.setAccount((Integer) session.getAttribute("account"));
        account.setPassword(hash);
        account.setSalt(salt);
        account.setIdentity((String)session.getAttribute("role"));
        accountService.update(account);
        session.invalidate();
        return "changesuccess";
    }

}
